package com.version1.diabeco.data.ajustes.medicamentos;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.version1.diabeco.data.AbstractDao;
import com.version1.diabeco.data.DiabecoContract;
import com.version1.diabeco.data.comida.AlimentoDaoImpl;
import com.version1.diabeco.data.medicacion.MedicacionDaoImpl;
import com.version1.diabeco.model.ajustes.medicamento.Medicamento;

public class MedicamentoDaoImpl extends AbstractDao implements MedicamentoDao {

	private Context context;
	private static MedicamentoDaoImpl instance;

	protected MedicamentoDaoImpl(Context context) {
		super(context);
	}

	/**
	 * Retrieves the singleton instance. Receives a context which is used for database initialization but also stored
	 * for subsequent sql operation calls.
	 * 
	 * This method is thread-safe.
	 * 
	 * @return MedicacionDao with the instance.
	 */
	public static synchronized MedicamentoDaoImpl getInstance(Context context) {
		if (instance == null) {
			instance = new MedicamentoDaoImpl(context);
		}

		instance.setContext(context);

		return instance;
	}

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	@Override
	public Long count() {
		// TODO Auto-generated method stub
		return null;
	}

	public Medicamento selectById(Long id) {

		Medicamento result = null;

		SQLiteDatabase db = MedicamentoDaoImpl.getInstance(this.getContext()).getReadableDatabase();

		// Define a projection that specifies which columns from the database
		// you will actually use after this query.
		String[] fields = { DiabecoContract.Medicamento._ID, 
							DiabecoContract.Medicamento.COLUMNA_ALIAS,
							DiabecoContract.Medicamento.COLUMNA_TIPO,
							DiabecoContract.Medicamento.COLUMNA_DESCRIPCION };

		String selection = DiabecoContract.Medicamento._ID + " = ?";
		String[] selectionArgs = { id.toString() };

		// How you want the results sorted in the resulting Cursor
		String sortOrder = DiabecoContract.Medicamento.COLUMNA_DESCRIPCION + " ASC";

		Cursor cursor = db.query(DiabecoContract.Medicamento.TABLE_NAME, // The table to query
				fields, // The columns to return
				selection, // The columns for the WHERE clause
				selectionArgs, // The values for the WHERE clause
				null, // don't group the rows
				null, // don't filter by row groups
				sortOrder // The sort order
				);

		result = this.retrieveMedicamentoFromCursor(cursor);
		db.close();
		return result;
	}

	
	@Override
	public List<Medicamento> selectAll() {

		List<Medicamento> result = new ArrayList<Medicamento>();

		SQLiteDatabase db = MedicacionDaoImpl.getInstance(this.getContext()).getReadableDatabase();

		// Define a projection that specifies which columns from the database
		// you will actually use after this query.
		String[] fields = { DiabecoContract.Medicamento._ID, DiabecoContract.Medicamento.COLUMNA_ALIAS,
				DiabecoContract.Medicamento.COLUMNA_TIPO,
				DiabecoContract.Medicamento.COLUMNA_DESCRIPCION,
				DiabecoContract.Medicamento.COLUMNA_ICON_RESOURCE_ID };

//		String selection = DiabecoContract.Medicamento.COLUMNA_FECHA + " >= ?";
//		String[] selectionArgs = { ultimosCincoDias.toString() };

		// How you want the results sorted in the resulting Cursor
		String sortOrder = DiabecoContract.Medicamento.COLUMNA_DESCRIPCION + " ASC";

		Cursor cursor = db.query(DiabecoContract.Medicamento.TABLE_NAME, // The table to query
				fields, // The columns to return
				null, // The columns for the WHERE clause
				null, // The values for the WHERE clause
				null, // don't group the rows
				null, // don't filter by row groups
				sortOrder // The sort order
				);

		while (cursor.moveToNext()) {
			Medicamento medicamento = this.retrieveMedicamentoFromCursor(cursor);
			result.add(medicamento);
		}

		db.close();
		return result;
	}

	private Medicamento retrieveMedicamentoFromCursor(Cursor cursor) {

		Medicamento medicamento = new Medicamento();
		Long id = cursor.getLong(cursor.getColumnIndexOrThrow(DiabecoContract.Medicamento._ID));
		String alias = cursor.getString(cursor.getColumnIndexOrThrow(DiabecoContract.Medicamento.COLUMNA_ALIAS));
		String tipo = cursor.getString(cursor.getColumnIndexOrThrow(DiabecoContract.Medicamento.COLUMNA_TIPO));
		String descripcion = cursor.getString(cursor.getColumnIndexOrThrow(DiabecoContract.Medicamento.COLUMNA_DESCRIPCION));
		Integer iconResourceId = cursor.getInt(cursor.getColumnIndexOrThrow(DiabecoContract.Medicamento.COLUMNA_ICON_RESOURCE_ID));

		medicamento.setId(id);
		medicamento.setAlias(alias);
		medicamento.setTipo(tipo);
		medicamento.setDescripcion(descripcion);
		medicamento.setIconResourceId(iconResourceId);

		System.out.println("Readed physical exercise measure: " + medicamento);

		return medicamento;

	}

	@Override
	public List<Medicamento> selectBetweenDates(Date from, Date to) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void save(Medicamento medicamento) {

		// Gets the data repository in write mode
		SQLiteDatabase db = AlimentoDaoImpl.getInstance(this.getContext()).getWritableDatabase();

		// Create a new map of values, where column names are the keys
		ContentValues values = new ContentValues();
		values.put(DiabecoContract.Medicamento.COLUMNA_TIPO, medicamento.getTipo());
		values.put(DiabecoContract.Medicamento.COLUMNA_DESCRIPCION, medicamento.getDescripcion());
		values.put(DiabecoContract.Medicamento.COLUMNA_ALIAS, medicamento.getAlias());
		values.put(DiabecoContract.Medicamento.COLUMNA_ICON_RESOURCE_ID, medicamento.getIconResourceId());

	
		long rowId;
		if (medicamento.getId() != null) {
			rowId = db.update(DiabecoContract.Medicamento.TABLE_NAME, values,
					DiabecoContract.Medicamento._ID + " = ?", new String[] { medicamento.getId().toString() });
		} else {
			// Insert the new row, returning the primary key value of the new row
			rowId = db.insert(DiabecoContract.Medicamento.TABLE_NAME, null, values);
		}
		
		System.out.println("Registros grabados en la base de datos: " + rowId);
		db.close();
	}

	
	@Override
	public void deleteById(Long id) {
		// Gets the data repository in write mode
		SQLiteDatabase db = MedicamentoDaoImpl.getInstance(this.getContext()).getWritableDatabase();

		String removeId = id.toString();

		int rowsDeleted = db.delete(DiabecoContract.Medicamento.TABLE_NAME, DiabecoContract.Medicamento._ID + "=?",
				new String[] { removeId });

		if (rowsDeleted != 1) {
			throw new RuntimeException("No se pudo eliminar el registro con id " + id);
		}

		// Cerramos Base de Datos
		db.close();
	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub

	}

}
